# 新闻详情页面驶入
from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, Comment,CommentLike, User
from info.modules.news import news_url
from info.response_code import RET
from info.utils.common import user_logo_data


@news_url.route("/<int:news_id>")
@user_logo_data
def detail(news_id):
    '''新闻视图详情页面'''
    # 取到用户的ID
    user=g.user

    # 右侧新闻排行
    news_list=None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.OTHER_NEWS_PAGE_MAX_COUNT)
    except Exception as e:
        return  jsonify(errno=RET,errmsg="数据库查询错误")
    # 定义一个空的字典列表，里面装的就是字典
    news_dict_li=[]
    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    news_obj=None
    try:
        news_obj = News.query.get(news_id)
    except Exception as e :
        current_app.logger.error(e)
    if not news_obj:
        abort(404)

    news_obj.clicks += 1

    is_collected=False

    if user and news_obj in (user.collection_news):
        is_collected=True

    # 获取评论的内容
    # 如果comment没有值默认为空
    comments=[]

    try:
        comments=Comment.query.filter(Comment.news_id==news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_list = []
    if g.user:

        for comment in comments:
            # 吧comment里面的字典拿出来
            comment_dict=comment.to_dict()
            # 在to_dict 里面添加is_like键值对，为后面页面显示点赞做铺垫
            comment_dict['is_like'] = False

            if comment :
                # 查询每条评论是否有赞
                print(type(comment))
                comm_like=CommentLike.query.filter(CommentLike.user_id==user.id,CommentLike.comment_id==comment.id).first()
                if comm_like:
                    comment_dict['is_like']=True
            comment_list.append(comment_dict)
    is_flowered=False
    flower=''
    try:
        flower = news_obj.user.followers.filter(User.id==user.id).all()
    except Exception as e:
        current_app.logger.error(e)

    if flower:
        is_flowered=True


    data={
        'user':user.to_dict() if user else None,
        'click_news_list':news_dict_li,
        'news':news_obj.to_dict(),
        'is_collected':is_collected,
        "comments":comment_list,
        'is_folowed':is_flowered


    }
    return render_template('news/detail.html',data=data)

@news_url.route('/followed_user',methods=['POST'])
@user_logo_data
def followed_user():
    '''用户关注与取消关注'''
    user=g.user
    if not user:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 获取新闻作者和关注动作
    user_id = request.json.get("user_id")
    action = request.json.get('action')

    if not all([action,user_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    if action not in ('follow','unfollow') :
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    target_user=''
    # 获取新闻作者的对象
    try:
        target_user=User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if  not target_user  :
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 判断动作
    if action == 'follow':
        # 判断是否已经关注
        if target_user not in user.followed :
            user.followed.append(target_user)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg='已经关注过该用户')
    else:
        if target_user  in user.followed:
            user.followed.remove(target_user)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg='你还没有关注过该用户')
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    return jsonify(errno=RET.OK, errmsg="操作成功")

@news_url.route('/news_collect',methods=['POST'])
@user_logo_data
def user_collection():
    """新闻收藏"""
    user=g.user
    if not user:

        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 接受新闻的id和是否收藏的状态
    new_id = request.json.get('news_id','')
    active = request.json.get('action','')
    # 校验新闻id 和 收藏是否有数据
    if not all ([new_id,active]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 判断active是在
    if active not in (['collect','cancel_collect']):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        new_id=int(new_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

    try:
        news = News.query.get(new_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

    if active=='collect':

        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news  in user.collection_news:
            user.collection_news.remove(news)

    return jsonify(errno=RET.OK,errmsg='OK')

@news_url.route('/news_comment',methods=['POST'])
@user_logo_data
def news_comment():
    """
    添加新闻评论
    :return:
    """

    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    news_id = request.json.get('news_id')
    comments_content= request.json.get("comment")
    parent_id = request.json.get('parent_id')

    if not  all([news_id,comments_content]):

        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 校验参数
    try:
        if news_id:
            news_id=int(news_id)
            if parent_id:
                parent_id=int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 数据查询
    try:
        news = News.query.get(news_id)
    except Exception as e :
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    if not news:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 初始化一个Comment对象
    comment=Comment()
    # 添加数据
    comment.news_id=news.id
    comment.user_id=user.id
    comment.content=comments_content
    if parent_id:
        comment.parent_id=parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)


    return jsonify(errno=RET.OK,errmsg="OK",data = comment.to_dict())



@news_url.route('/comment_like',methods=["POST"])
@user_logo_data
def comment_like():
    """
    post /news/comment_like
    参数: json
    comment_id, action
    评论点赞

返回值:json
    :return:
    """

    user=g.user
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")


    if not all([comment_id,action]):
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    if action not in (['add','remove']):
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 查询评论，并判断评论是否存在
    try:
        comment=Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='没有查找到数据')

    if action=='add':
        comment_like = CommentLike.query.filter(CommentLike.comment_id==comment_id,CommentLike.user_id==user.id).first()
        if not comment_like :
            comm_like = CommentLike()
            comm_like.user_id = user.id
            comm_like.comment_id=comment_id
            try:
                db.session.add(comm_like)
                db.session.commit()
            except Exception as e :
                current_app.logger.error(e)
                db.session.rollback()
            comment.like_count += 1

    if action == "remove":
        comment_like = CommentLike.query.filter(CommentLike.comment_id==comment_id,CommentLike.user_id==user.id).first()
        if comment_like:
            try:
                db.session.delete(comment_like)
                db.session.commit()
            except Exception as e:
                current_app.logger.error()
                db.session.rollback()
            comment.like_count -= 1

    return jsonify(errno=RET.OK, errmsg="OK")





